<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form label-width="110px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="节点名称">
              <el-input @change="onSearch" clearable class="form-width" v-model="formSearch.keyword"
                placeholder="输入节点名称"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <!-- <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p> -->
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="primary" @click="dialogFormVisible = true; formType = 'add'"
            v-if="$isPer(permission, ['acceptanceNodes_add'])">添加验收节点</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList">
      <div class="list-top-box">
        <p class="list-top-box-left">
          已选 <span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }} 数据
        </p>
        <div class="list-top-box-right">
          <el-button type="primary" :disabled="multipleSelection.length != 1" @click="editFunc"
            v-if="$isPer(permission, ['acceptanceNodes_edit'])">编辑</el-button>
          <el-button type="danger" plain :disabled="multipleSelection.length == 0" @click="delFunc"
            v-if="$isPer(permission, ['acceptanceNodes_del'])">删除</el-button>
        </div>
      </div>
      <div class="table-box" v-loading="tableLoading">
        <el-table ref="table" :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData" highlight-selection-row border
          @selection-change="handleSelectionChange" @row-click="handleHighlightChangeTable" height="100%">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column min-width="180px" prop="node_name" label="节点名称" show-overflow-tooltip></el-table-column>
          <!-- <el-table-column min-width="180px" prop="project_number" label="类型" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.type == 1 ? '验收节点' : '验收标准' }}</span>
            </template>
</el-table-column> -->
          <el-table-column min-width="180px" prop="created_at" label="创建时间" show-overflow-tooltip>
            <template slot-scope="scope">{{ $dateTimeToDate(scope.row.created_at) }}</template>
          </el-table-column>
          <el-table-column min-width="180px" prop="handlers_name" label="创建人" show-overflow-tooltip></el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog destroy-on-close :title="formType == 'add' ? '添加验收节点' : '修改验收节点'" :visible.sync="dialogFormVisible"
      :modal-append-to-body="false" @close="visibleClose" :close-on-click-modal="false" width="460px">
      <el-form :model="formData" :rules="formRules" class="user-info" ref="dialogFrom" label-width="110px"
        label-position="left">
        <el-form-item label="验收节点" prop="name">
          <el-input v-model="formData.name" placeholder="请输入验收节点"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSubmit" :loading="submitBtn">提交</el-button>
        <el-button @click="visibleClose">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import nodesApi from '@/api/nodesApi'

export default {
  name: "acceptanceNodesList",
  data() {
    return {
      tableLoading: false,//列表loading
      tableData: [],//列表数据
      formSearch: { keyword: '' },//搜索form
      moreSearchShow: false,//
      page: 1,
      num: 10,
      total: 0,
      multipleSelection: [],//多选数据

      // 弹窗
      formType: 'add',
      dialogFormVisible: false,
      submitBtn: false,
      formData: {
        id: '',
        name: '',
      },
      formRules: {
        name: [{ required: true, message: "请输入验收节点", trigger: "change" }],
      },
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {
  },
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })

    this.getList();
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == 'number' ? page : this.page;
      this.getList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    editFunc() {
      let item = this.multipleSelection[0]
      this.formType = 'update'
      this.formData.id = item.id
      this.formData.name = item.node_name
      this.dialogFormVisible = true
      console.log(item)
    },
    delFunc() {
      let multipleSelection = this.multipleSelection;
      let id_arr = multipleSelection.map(item => item.id)
      let name_arr = multipleSelection.map(item => item.node_name)
      this.$confirm('是否删除【' + name_arr.join(', ') + '】?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log(id_arr)
        nodesApi.delNodes({ id_arr }).then((res) => {
          console.log(res, "删除验收节点");
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.onSearch();
          } else {
            this.$message.error(res.message);
          }
        });
      }).catch(() => { });

    },
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },

    // 弹窗
    visibleClose() {
      this.$refs['dialogFrom'].resetFields();
      this.dialogFormVisible = false;
    },
    saveSubmit() {
      this.$refs['dialogFrom'].validate((valid) => {
        if (valid) {
          this.submitBtn = true
          let formData = this.formData;
          if (this.formType == 'add') {
            nodesApi.addNodes({
              node_name: formData.name,
              type: 1
            }).then(res => {
              console.log(res, '新增验收节点')
              if (res.code == 200) {
                this.visibleClose()
                this.onSearch(1)
              } else {
                this.$message.warning(res.message)
              }
              this.submitBtn = false
            })
          } else {
            nodesApi.updNodes({
              node_id: formData.id,
              node_name: formData.name,
            }).then(res => {
              console.log(res, '更新验收节点')
              if (res.code == 200) {
                this.visibleClose()
                this.onSearch()
              } else {
                this.$message.warning(res.message)
              }
              this.submitBtn = false
            })
          }
        } else {
          return false;
        }
      });
    },

    // 获取列表数据
    getList() {
      this.tableLoading = true;
      nodesApi.getNodesList({
        page: this.page,
        num: this.num,
        type: 1,
        keyword: this.formSearch.keyword,
      }).then((res) => {
        console.log(res, "获取列表");
        this.tableLoading = false;
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      }).catch((err) => {
        this.$message({
          message: err.message,
          type: "warning",
        });
      });
    }
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss';
</style>